import express from 'express';
import { randomUUID } from 'node:crypto';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import cors from 'cors';

// Create MCP server that wraps existing HTTP API endpoints
export function createApiMcpServer() {
  const server = new McpServer({
    name: 'seller-management-api-wrapper',
    version: '1.0.0',
    description: 'MCP server that wraps existing seller management HTTP API endpoints'
  });

  // Helper function to make HTTP requests to the existing API
  async function callApi(endpoint: string, method: string = 'GET', body?: any) {
    const baseUrl = 'http://localhost:3000'; // Next.js dev server
    const url = `${baseUrl}${endpoint}`;
    
    try {
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: body ? JSON.stringify(body) : undefined,
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      return await response.json();
    } catch (error: any) {
      console.error(`API call failed to ${endpoint}:`, error);
      throw new Error(`API调用失败: ${error.message}`);
    }
  }

  // Helper function to get status text
  function getStatusText(status: string): string {
    const statusMap: Record<string, string> = {
      'pending': '待支付',
      'paid': '已支付',
      'shipped': '已发货',
      'delivered': '已交付',
      'cancelled': '已取消'
    };
    return statusMap[status] || status;
  }

  // Order Management Tools that wrap HTTP API endpoints

  server.registerTool(
    'get-order',
    {
      title: '获取订单详情',
      description: '根据订单ID获取订单详细信息，调用 /api/orders/[id] API',
      inputSchema: {
        orderId: z.number().describe('订单ID')
      }
    },
    async ({ orderId }) => {
      try {
        const order = await callApi(`/api/orders/${orderId}`);
        
        const orderText = `订单 #${order.id}
客户: ${order.customerName} (${order.customerEmail || '无邮箱'})
状态: ${getStatusText(order.status)}
总金额: ¥${order.totalAmount}
创建时间: ${new Date(order.createdAt * 1000).toLocaleString('zh-CN')}
更新时间: ${new Date(order.updatedAt * 1000).toLocaleString('zh-CN')}`;

        const itemsText = order.items.map((item: any) => 
          `- ${item.productName}: ${item.quantity} × ¥${item.productPrice} = ¥${item.subtotal}`
        ).join('\n');

        const result = `${orderText}\n\n商品明细:\n${itemsText}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `获取订单详情失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'update-order-status',
    {
      title: '更新订单状态',
      description: '更新订单状态，调用 /api/orders/[id] PUT API',
      inputSchema: {
        orderId: z.number().describe('订单ID'),
        status: z.enum(['pending', 'paid', 'shipped', 'delivered', 'cancelled']).describe('新状态'),
        cancelReason: z.string().optional().describe('取消原因（仅当状态为cancelled时有效）')
      }
    },
    async ({ orderId, status, cancelReason }) => {
      try {
        const updateData: any = { status };
        if (status === 'cancelled' && cancelReason) {
          updateData.cancelReason = cancelReason;
        }

        const result = await callApi(`/api/orders/${orderId}`, 'PUT', updateData);

        return {
          content: [{ type: 'text', text: `订单 ${orderId} 状态已更新为 ${getStatusText(status)}` }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `更新订单状态失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'list-orders',
    {
      title: '订单列表查询',
      description: '查询订单列表，调用 /api/orders API',
      inputSchema: {
        status: z.string().optional().describe('订单状态: pending, paid, shipped, delivered, cancelled'),
        customerName: z.string().optional().describe('客户名称'),
        limit: z.number().optional().default(10).describe('返回数量限制')
      }
    },
    async ({ status, customerName, limit }) => {
      try {
        // For simplicity, we'll implement client-side filtering for complex queries
        const orders = await callApi('/api/orders');
        
        let filteredOrders = orders;
        
        if (status) {
          filteredOrders = filteredOrders.filter((order: any) => order.status === status);
        }
        
        if (customerName) {
          filteredOrders = filteredOrders.filter((order: any) => 
            order.customerName && order.customerName.includes(customerName)
          );
        }
        
        if (limit) {
          filteredOrders = filteredOrders.slice(0, limit);
        }

        const ordersText = filteredOrders.map((order: any) => 
          `#${order.id} | ${getStatusText(order.status)} | ¥${order.totalAmount} | ${order.customerName} | ${new Date(order.createdAt * 1000).toLocaleDateString('zh-CN')}`
        ).join('\n');

        const result = `找到 ${filteredOrders.length} 个订单\n\n${ordersText || '未找到符合条件的订单'}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `查询订单列表失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  // Customer Management Tools

  server.registerTool(
    'get-customer',
    {
      title: '获取客户信息',
      description: '根据客户ID获取客户详细信息，调用 /api/customers/[id] API',
      inputSchema: {
        customerId: z.number().describe('客户ID')
      }
    },
    async ({ customerId }) => {
      try {
        const customer = await callApi(`/api/customers/${customerId}`);

        const result = `客户 #${customer.id}
姓名: ${customer.name}
邮箱: ${customer.email || '无'}
电话: ${customer.phone || '无'}
地址: ${customer.address || '无'}
创建时间: ${new Date(customer.createdAt * 1000).toLocaleString('zh-CN')}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `获取客户信息失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'search-customers',
    {
      title: '搜索客户',
      description: '搜索客户，调用 /api/customers API',
      inputSchema: {
        searchTerm: z.string().describe('搜索关键词（名称、邮箱或电话）'),
        limit: z.number().optional().default(10).describe('返回数量限制')
      }
    },
    async ({ searchTerm, limit }) => {
      try {
        const customers = await callApi('/api/customers');
        
        const filteredCustomers = customers.filter((customer: any) => 
          customer.name.includes(searchTerm) ||
          (customer.email && customer.email.includes(searchTerm)) ||
          (customer.phone && customer.phone.includes(searchTerm))
        ).slice(0, limit || 10);

        if (filteredCustomers.length === 0) {
          return {
            content: [{ type: 'text', text: `未找到匹配 "${searchTerm}" 的客户` }]
          };
        }

        const customersText = filteredCustomers.map((customer: any) => 
          `#${customer.id} | ${customer.name} | ${customer.email || '无邮箱'} | ${customer.phone || '无电话'}`
        ).join('\n');

        const result = `找到 ${filteredCustomers.length} 个客户:\n\n${customersText}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `搜索客户失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'create-customer',
    {
      title: '创建客户',
      description: '创建新客户，调用 /api/customers POST API',
      inputSchema: {
        name: z.string().describe('客户姓名（必填）'),
        email: z.string().email().optional().describe('邮箱地址'),
        phone: z.string().optional().describe('手机号码'),
        phone2: z.string().optional().describe('备用电话'),
        phone2Purpose: z.string().optional().describe('备用电话用途'),
        wechat: z.string().optional().describe('微信号'),
        wechatPurpose: z.string().optional().describe('微信用途'),
        qq: z.string().optional().describe('QQ号'),
        qqPurpose: z.string().optional().describe('QQ用途'),
        whatsapp: z.string().optional().describe('WhatsApp'),
        whatsappPurpose: z.string().optional().describe('WhatsApp用途'),
        telegram: z.string().optional().describe('Telegram'),
        telegramPurpose: z.string().optional().describe('Telegram用途'),
        address: z.string().optional().describe('地址')
      }
    },
    async (customerData) => {
      try {
        // 验证必填字段
        if (!customerData.name || customerData.name.trim() === '') {
          return {
            content: [{ type: 'text', text: '创建客户失败: 客户姓名不能为空' }],
            isError: true
          };
        }

        const newCustomer = await callApi('/api/customers', 'POST', customerData);

        const result = `客户创建成功！
客户ID: ${newCustomer.id}
姓名: ${newCustomer.name}
邮箱: ${newCustomer.email || '未设置'}
电话: ${newCustomer.phone || '未设置'}
地址: ${newCustomer.address || '未设置'}
创建时间: ${new Date(newCustomer.createdAt * 1000).toLocaleString('zh-CN')}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        // 处理邮箱重复错误
        let errorMessage = `创建客户失败: ${error.message}`;
        if (error.message.includes('邮箱已存在')) {
          errorMessage = '创建客户失败: 邮箱地址已被其他客户使用，请使用其他邮箱';
        }
        
        return {
          content: [{ type: 'text', text: errorMessage }],
          isError: true
        };
      }
    }
  );

  // Product Management Tools

  server.registerTool(
    'get-product',
    {
      title: '获取产品信息',
      description: '根据产品ID获取产品详细信息，调用 /api/products/[id] API',
      inputSchema: {
        productId: z.number().describe('产品ID')
      }
    },
    async ({ productId }) => {
      try {
        const product = await callApi(`/api/products/${productId}`);

        const result = `产品 #${product.id}
名称: ${product.name}
描述: ${product.description || '无'}
价格: ¥${product.price}
分类: ${product.category || '未分类'}
SKU: ${product.sku || '无'}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `获取产品信息失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'list-products',
    {
      title: '产品列表查询',
      description: '查询产品列表，调用 /api/products API',
      inputSchema: {
        category: z.string().optional().describe('产品分类'),
        limit: z.number().optional().default(10).describe('返回数量限制')
      }
    },
    async ({ category, limit }) => {
      try {
        const products = await callApi('/api/products');
        
        let filteredProducts = products;
        
        if (category) {
          filteredProducts = filteredProducts.filter((product: any) => 
            product.category === category
          );
        }
        
        if (limit) {
          filteredProducts = filteredProducts.slice(0, limit);
        }

        if (filteredProducts.length === 0) {
          return {
            content: [{ type: 'text', text: '未找到符合条件的商品' }]
          };
        }

        const productsText = filteredProducts.map((product: any) => 
          `#${product.id} | ${product.name} | ¥${product.price} | ${product.category || '未分类'} | ${product.sku || '无SKU'}`
        ).join('\n');

        const result = `找到 ${filteredProducts.length} 个商品:\n\n${productsText}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `查询产品列表失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  // Inventory Management Tools that wrap HTTP API endpoints

  server.registerTool(
    'check-inventory',
    {
      title: '检查库存状态',
      description: '检查产品库存状态和低库存预警，调用 /api/inventory API',
      inputSchema: {
        productId: z.number().optional().describe('产品ID（留空查询所有库存）'),
        showLowStockOnly: z.boolean().optional().default(false).describe('仅显示低库存产品')
      }
    },
    async ({ productId, showLowStockOnly }) => {
      try {
        const inventoryData = await callApi('/api/inventory');
        
        let filteredInventory = inventoryData;
        
        // Filter by product ID if specified
        if (productId) {
          filteredInventory = filteredInventory.filter((item: any) => item.productId === productId);
        }
        
        // Filter for low stock items if requested
        if (showLowStockOnly) {
          filteredInventory = filteredInventory.filter((item: any) => 
            item.quantity <= item.lowStockThreshold
          );
        }

        if (filteredInventory.length === 0) {
          const message = productId 
            ? `产品 ${productId} 的库存记录不存在`
            : showLowStockOnly 
              ? '没有低库存产品'
              : '没有库存记录';
          
          return {
            content: [{ type: 'text', text: message }]
          };
        }

        const inventoryText = filteredInventory.map((item: any) => {
          const status = item.quantity === 0 
            ? '缺货' 
            : item.quantity <= item.lowStockThreshold 
              ? '低库存' 
              : '正常';
          
          return `#${item.productId} | ${item.productName} | ${item.quantity} 件 (阈值: ${item.lowStockThreshold}) | ${status} | SKU: ${item.productSku || '无'}`;
        }).join('\n');

        const result = `库存状态检查结果 (共 ${filteredInventory.length} 个产品):\n\n${inventoryText}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `检查库存失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'list-low-stock',
    {
      title: '低库存产品列表',
      description: '列出所有低库存或缺货的产品，调用 /api/inventory API',
      inputSchema: {
        limit: z.number().optional().default(20).describe('返回数量限制')
      }
    },
    async ({ limit }) => {
      try {
        const inventoryData = await callApi('/api/inventory');
        
        // Filter for low stock or out of stock items
        const lowStockItems = inventoryData.filter((item: any) => 
          item.quantity <= item.lowStockThreshold
        ).slice(0, limit || 20);

        if (lowStockItems.length === 0) {
          return {
            content: [{ type: 'text', text: '没有低库存或缺货的产品' }]
          };
        }

        const itemsText = lowStockItems.map((item: any) => {
          const status = item.quantity === 0 ? '缺货' : '低库存';
          return `#${item.productId} | ${item.productName} | ${item.quantity} 件 (阈值: ${item.lowStockThreshold}) | ${status} | ¥${item.productPrice || '未知'}`;
        }).join('\n');

        const result = `低库存或缺货产品 (共 ${lowStockItems.length} 个):\n\n${itemsText}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `获取低库存列表失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'update-inventory',
    {
      title: '更新库存数量',
      description: '更新产品库存数量，调用 /api/inventory POST API',
      inputSchema: {
        productId: z.number().describe('产品ID'),
        quantity: z.number().describe('新的库存数量'),
        lowStockThreshold: z.number().optional().describe('低库存阈值（可选）')
      }
    },
    async ({ productId, quantity, lowStockThreshold }) => {
      try {
        const updateData: any = { productId, quantity };
        if (lowStockThreshold !== undefined) {
          updateData.lowStockThreshold = lowStockThreshold;
        }

        const result = await callApi('/api/inventory', 'POST', updateData);

        return {
          content: [{ 
            type: 'text', 
            text: `产品 ${productId} 库存已更新为 ${quantity} 件${lowStockThreshold ? `，低库存阈值设置为 ${lowStockThreshold}` : ''}` 
          }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `更新库存失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  // Dashboard Resources that wrap HTTP API endpoints

  server.registerResource(
    'dashboard-stats',
    'dashboard://stats',
    {
      title: '仪表盘统计数据',
      description: '系统仪表盘的关键统计数据，调用 /api/dashboard/stats API',
      mimeType: 'application/json'
    },
    async (uri) => {
      try {
        const stats = await callApi('/api/dashboard/stats');
        
        return {
          contents: [{
            uri: uri.href,
            text: JSON.stringify(stats, null, 2)
          }]
        };
      } catch (error: any) {
        return {
          contents: [{
            uri: uri.href,
            text: JSON.stringify({ error: `获取统计数据失败: ${error.message}` }, null, 2)
          }]
        };
      }
    }
  );

  return server;
}

// Create and configure Express app for Streamable HTTP transport
export function createApiApp() {
  const app = express();
  app.use(express.json());

  // Enable CORS for browser clients
  app.use(cors({
    origin: '*',
    exposedHeaders: ['Mcp-Session-Id'],
    allowedHeaders: ['Content-Type', 'mcp-session-id']
  }));

  // Map to store transports by session ID
  const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};

  // MCP POST endpoint
  app.post('/mcp', async (req, res) => {
    try {
      let transport: StreamableHTTPServerTransport;
      
      if (!req.body || !isInitializeRequest(req.body)) {
        // For non-initialization requests, require session ID
        const sessionId = req.headers['mcp-session-id'] as string | undefined;
        if (!sessionId || !transports[sessionId]) {
          res.status(400).json({
            jsonrpc: '2.0',
            error: {
              code: -32000,
              message: 'Bad Request: No valid session ID provided',
            },
            id: null,
          });
          return;
        }
        transport = transports[sessionId];
      } else {
        // New initialization request
        transport = new StreamableHTTPServerTransport({
          sessionIdGenerator: () => randomUUID(),
          onsessioninitialized: (sessionId) => {
            // Store the transport by session ID
            transports[sessionId] = transport;
          }
        });

        // Clean up transport when closed
        transport.onclose = () => {
          if (transport.sessionId) {
            delete transports[transport.sessionId];
          }
        };

        // Create and connect MCP server
        const server = createApiMcpServer();
        await server.connect(transport);

        await transport.handleRequest(req, res, req.body);
        return;
      }

      // Handle request with existing transport
      await transport.handleRequest(req, res, req.body);
    } catch (error) {
      console.error('Error handling MCP request:', error);
      if (!res.headersSent) {
        res.status(500).json({
          jsonrpc: '2.0',
          error: {
            code: -32603,
            message: 'Internal server error',
          },
          id: null,
        });
      }
    }
  });

  // Handle GET requests for SSE streams
  app.get('/mcp', async (req, res) => {
    const sessionId = req.headers['mcp-session-id'] as string | undefined;
    if (!sessionId || !transports[sessionId]) {
      res.status(400).send('Invalid or missing session ID');
      return;
    }

    const transport = transports[sessionId];
    await transport.handleRequest(req, res);
  });

  // Handle DELETE requests for session termination
  app.delete('/mcp', async (req, res) => {
    const sessionId = req.headers['mcp-session-id'] as string | undefined;
    if (!sessionId || !transports[sessionId]) {
      res.status(400).send('Invalid or missing session ID');
      return;
    }

    const transport = transports[sessionId];
    await transport.handleRequest(req, res);
  });

  // Health check endpoint
  app.get('/health', (req, res) => {
    res.json({ 
      status: 'ok', 
      service: 'seller-management-api-mcp',
      type: 'http-api-wrapper',
      api_base_url: 'http://localhost:3000'
    });
  });

  return app;
}

// Export for standalone execution
export async function startApiServer(port = 3002) {
  const app = createApiApp();
  
  return new Promise((resolve) => {
    const server = app.listen(port, () => {
      console.log(`MCP API Wrapper Server running on port ${port}`);
      console.log(`Health check: http://localhost:${port}/health`);
      console.log(`MCP endpoint: http://localhost:${port}/mcp`);
      console.log('API Target: http://localhost:3000 (Next.js dev server)');
      console.log('Mode: HTTP API wrapper - reusing existing server logic');
      resolve(server);
    });

    // Handle graceful shutdown
    process.on('SIGINT', async () => {
      console.log('Shutting down MCP API server...');
      server.close(() => {
        console.log('API server shutdown complete');
        process.exit(0);
      });
    });
  });
}

// For standalone execution
if (import.meta.url === `file://${process.argv[1]}`) {
  const port = process.env.MCP_API_PORT ? parseInt(process.env.MCP_API_PORT) : 3002;
  startApiServer(port).catch(console.error);
}